package com.hexb.core.config

import com.google.common.base.Predicates
import com.google.common.collect.Sets
import com.hexb.core.properties.SwaggerProperties
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport
import springfox.documentation.builders.ApiInfoBuilder
import springfox.documentation.builders.ParameterBuilder
import springfox.documentation.builders.PathSelectors
import springfox.documentation.builders.RequestHandlerSelectors
import springfox.documentation.schema.ModelRef
import springfox.documentation.service.ApiInfo
import springfox.documentation.spi.DocumentationType
import springfox.documentation.spring.web.plugins.Docket
import springfox.documentation.swagger2.annotations.EnableSwagger2
import springfox.documentation.service.Parameter;


/**
 * @author hexb
 * @create 2017-11-02 10:49
 * */
@Configuration
@EnableSwagger2
@EnableConfigurationProperties([SwaggerProperties.class])
class SwaggerAutoConfiguration {

    @Autowired
    private SwaggerProperties swaggerProperties


    @Bean
    Docket createDocket() {
        def docket = new Docket(DocumentationType.SWAGGER_2)
                .protocols(Sets.newHashSet("http", "https"))
                .select()
                .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework")))
                .paths(PathSelectors.any())
                .paths(Predicates.not(PathSelectors.regex('/error.*')))
                .build()

        if (swaggerProperties?.oathuHeader) {
            docket.globalOperationParameters(headerParameter())
        }
        docket.apiInfo(apiInfo())

    }

    private ApiInfo apiInfo() {
        ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder()
        swaggerProperties?.with {
            apiInfoBuilder.title(title)
                    .description(description).version(version)
        }
        apiInfoBuilder.build()
    }

    private List<Parameter> headerParameter() {
        ParameterBuilder ticketPar = new ParameterBuilder()
        List<Parameter> pars = new ArrayList<Parameter>()
        ticketPar.name("Authorization").description("OAthu2 Token")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build()
        pars.add(ticketPar.build())
        return pars
    }
}
